package com.livestocksolutions.intent;

import java.util.Arrays;
import java.util.Date;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.livestocksolutions.Bovine;
import com.livestocksolutions.Join;
import com.livestocksolutions.LivestockSolutions;
import com.livestocksolutions.Mob;
import com.livestocksolutions.Observation;
import com.livestocksolutions.Paddock;
import com.livestocksolutions.R;
import com.livestocksolutions.ui.ListCattleArrayAdapter;
import com.livestocksolutions.ui.ListJoinArrayAdapter;
import com.livestocksolutions.ui.ListObservationArrayAdapter;
import com.livestocksolutions.ui.ViewCattleArrayAdapter;
import com.livestocksolutions.ui.ViewGroupMobArrayAdapter;
import com.livestocksolutions.ui.ViewJoinArrayAdapter;
import com.livestocksolutions.ui.ViewMobArrayAdapter;
import com.livestocksolutions.ui.ViewObservationArrayAdapter;
import com.livestocksolutions.util.StringArrayParcelable;

/* -- Version History --
 *  1.0 : 10 September 2012 - Initial version.
 */

/**
 * A class to create the layout for a Mob
 * @author Adam Parr
 * @version 1.0
 * 
 * @.modified 28 September 2012
 */
public class MobActivity extends GroupActivity {	
	/**
	 * Id of the paddock that this Mob is located in.
	 */
	protected long paddock = 0;
	
	/**
	 * Constructor
	 */
	public MobActivity() {
		super(RESOURCEID);
	}
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
    	super.create(savedInstanceState);
        
    	if(stack.size()==0){
    		setContentView(RESOURCEID[GROUPVIEW]);
    		if(!built){
    			// Put the ID of this Mob Object
	            id = id!=-1?id:getIntent().getExtras().getLong(ITEMID,-1);
	            Mob m = (Mob) LivestockSolutions.getGroupByID(id);
    			// Read initial state of the Mob Object
	            String[] groupType = new String[ViewMobArrayAdapter.SIZE];
	            groupType[ViewGroupMobArrayAdapter.ID] 			= String.valueOf(m.getID());
	            groupType[ViewGroupMobArrayAdapter.NAME] 		= m.getName();
	            groupType[ViewGroupMobArrayAdapter.DESCRIPTION] 	= m.getDescription();
	            groupType[ViewMobArrayAdapter.LOCATION] 	= String.valueOf(paddock=m.getLocation()!=null?m.getLocation().getID():0);
    			
	            Bovine[] bovineList = m.getBovineList();
	            Arrays.sort(bovineList, bovineComparator);
	            String[][] cattleValues = new String[bovineList.length][];
	            for(int x=0; x<bovineList.length; x++){
	            	Date dobDate =  bovineList[x].getDob();
	            	
	            	String[] item = new String[ListCattleArrayAdapter.SIZE];
	            	item[ViewCattleArrayAdapter.ID]=String.valueOf(bovineList[x].getID());
	            	item[ViewCattleArrayAdapter.VISUALID]=bovineList[x].getEartag().getEartagID();
	            	item[ViewCattleArrayAdapter.NLISRFID]=bovineList[x].getEartag().getRfID();
	            	item[ViewCattleArrayAdapter.DOB]=dobDate!=null?String.valueOf(dobDate.getTime()):"0";
	    			
	            	cattleValues[x]=item;
	            }
	            
	            Observation[] observationList = m.getObservations();
	            Arrays.sort(observationList, observationComparator);
	            String[][] observationValues = new String[observationList.length][];
	            for(int x=0; x<observationList.length; x++){
	            	String[] item = new String[ViewObservationArrayAdapter.SIZE];
	            	item[ViewObservationArrayAdapter.ID]=String.valueOf(observationList[x].getID());
	            	item[ViewObservationArrayAdapter.DATE]=String.valueOf(observationList[x].getDate().getTime());
	            	item[ViewObservationArrayAdapter.TYPE]=String.valueOf(observationList[x].getPriority());
	            	item[ViewObservationArrayAdapter.VALUE]=observationList[x].getComment();
	    			
	            	observationValues[x]=item;
	            }
	            
	            Join[] joinList = m.getCurrentJoinings();
	            Arrays.sort(joinList, joinComparator);
	            String[][] joinValues = new String[joinList.length][];
	            for(int x=0; x<joinList.length; x++){
	            	String[] item = new String[ViewJoinArrayAdapter.SIZE];
	            	item[ViewJoinArrayAdapter.ID]=String.valueOf(joinList[x].getID());
	            	item[ViewJoinArrayAdapter.INSERTIONDATE]=String.valueOf(joinList[x].getInsertionDate().getTime());
	            	item[ViewJoinArrayAdapter.REMOVALDATE]=String.valueOf(joinList[x].getRemovalDate().getTime());
	            	item[ViewJoinArrayAdapter.COUNT]=String.valueOf(joinList[x].getCows().length);
	    			
	            	joinValues[x]=item;
	            }
    			
    			groupView = new ViewMobArrayAdapter(this, groupType);
    			cattle = new ListCattleArrayAdapter(this, cattleValues);
    	    	observations = new ListObservationArrayAdapter(this, observationValues);
    	    	joins = new ListJoinArrayAdapter(this, joinValues);
    	    	
		    	setPage();
		    	drawMembers();
	            
				currentState.putInt(STATEID,GROUPVIEW);
				built=true;
    		}
    	}
    }
    
    @Override
    public void onSaveInstanceState (Bundle outState) {
    	super.onSaveInstanceState (outState);
    	
    	outState.putParcelable("mobType", new StringArrayParcelable().setStrings(groupView.get()));
    	outState.putParcelable("mobJoin", new StringArrayParcelable().setStrings(joins.get()));
    	
    	outState.putLong("paddock", paddock);
    }
    
    @Override
    public void onRestoreInstanceState(Bundle inState) {
    	groupView = new ViewMobArrayAdapter(this,((StringArrayParcelable)inState.getParcelable("mobType")).getStrings()[0]);
    	joins = new ListJoinArrayAdapter(this,((StringArrayParcelable)inState.getParcelable("mobJoin")).getStrings());
    	
    	paddock = inState.getLong("paddock");
    	
    	super.onRestoreInstanceState (inState);
    }
    
    @Override
    public boolean frameSelection(int frame) {
        switch (frame) {
        	case R.id.menu_save:
        		if(groupView.isValid()){
	        		edit = false;
	        		
	        		Mob m = id==-1?new Mob(groupView.get()[0][ViewGroupMobArrayAdapter.NAME]):(Mob)LivestockSolutions.getGroupByID(id);
	        		m.setName(groupView.get()[0][ViewGroupMobArrayAdapter.NAME]);
	        		m.setDescription(groupView.get()[0][ViewGroupMobArrayAdapter.DESCRIPTION]);
	        		m.setLocation((Paddock)LivestockSolutions.getLocationByID(Long.parseLong(groupView.get()[0][ViewMobArrayAdapter.LOCATION])));
	        		
	        		id=m.getID();
	        		if(LivestockSolutions.addGroup(m)){
	        			Toast.makeText(this,getResources().getString(R.string.message_saved,getResources().getString(R.string.cattle_mob)),Toast.LENGTH_SHORT).show();
	        		}else{
	        			Toast.makeText(this,getResources().getString(R.string.message_errorSave,getResources().getString(R.string.cattle_mob),getResources().getString(R.string.message_unknown)),Toast.LENGTH_SHORT).show();
	        		}
	        		
	        		built=false;
	        		onPrepareOptionsMenu(menu);
	        		showView(currentState.getInt(STATEID,GROUPVIEW),currentState);
	        		// Pop current view
	        		stack.pop();
	        		// Pop edit change
	        		stack.pop();
	        		break;
        		}
		        //$FALL-THROUGH$
			default:
	            return super.frameSelection(frame);
        }
        return true;
    }
	
	@Override
    protected void setPage(){
    	LinearLayout itemView = (LinearLayout) findViewById(R.id.listView);
    	if(edit){
			((ViewMobArrayAdapter)groupView).setModifyMob();
	    }else{
	    	((ViewMobArrayAdapter)groupView).setViewMob();
	    }
    	
    	if(itemView != null){
    		// Get a list of Paddocks.
    		Paddock[] paddocks = LivestockSolutions.getOnlyPaddocks();
    		String[][] paddockValues = new String[paddocks.length+1][];
    		
    		String[] noPaddock = new String[2];
    		noPaddock[ViewGroupMobArrayAdapter.ID] = String.valueOf(0);
    		noPaddock[ViewGroupMobArrayAdapter.NAME] = getResources().getString(R.string.paddock_none);
    		paddockValues[0]=noPaddock;
    		
    		for(int x=0; x<paddocks.length; x++){
    			String[] item = new String[2];
    			item[ViewGroupMobArrayAdapter.ID] = String.valueOf(paddocks[x].getID());
    			item[ViewGroupMobArrayAdapter.NAME] = paddocks[x].getName();
    			
    			paddockValues[x+1]=item;
    		}

    		((ViewMobArrayAdapter) groupView).setPaddockList(paddockValues);
    		
    		groupView.setRoot(itemView);
    		View v = groupView.getView(0,null, itemView);
    		if(edit || id==-1){
				
			}else{
				View d = v.findViewById(R.id.mobPaddockList);
				d.setEnabled(paddock>0);
				if(paddock>0){
		    		d.setOnClickListener(new View.OnClickListener() {
						public void onClick(View v) {
							Intent intent = new Intent(MobActivity.this, PaddockActivity.class);
							intent.putExtra(ITEMID, paddock);
					    	startActivityForResult(intent, EXISTING);
						}
					});
				}
			}
    		
	    	itemView.addView(v,0);
    	}
    }
}
